package com.magician.transaction.proxy;

import com.magician.jdbc.core.transaction.TransactionManager;
import com.magician.transaction.annotation.Transaction;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 事务控制
 */
public class TransactionProxy implements MethodInterceptor {

    /**
     * 获取代理对象
     *
     * @param clazz bean的class
     * @return 对象
     */
    public Object getProxy(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        // 设置需要创建子类的类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        // 通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    /**
     * 绑定代理
     *
     * @param o
     * @param method
     * @param args
     * @param methodProxy
     * @return obj
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Transaction transaction = method.getAnnotation(Transaction.class);
        try {
            if(transaction != null){
                TransactionManager.beginTraction(transaction.level());
            }

            Object result = methodProxy.invokeSuper(o, args);

            if(transaction != null){
                TransactionManager.commit();
            }

            return result;
        } catch (Exception e){
            if(transaction != null) {
                TransactionManager.rollback();
            }
            throw e;
        }
    }
}
